﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pay.Service {
    public class TokenBazaarProductService : ServiceBase, ITokenBazaarProductService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        public TokenBazaarProductService(IUnitOfWork iUnitOfWork) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
        }
        /// <summary>
        /// 新增修改商品
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SaveProduct(token_bazaar_product_base_dto model) {
            var merchant = context.Merchants.FindById(model.merchant_id);
            if (merchant.UserType < UserType.tokenMaker) {
                throw new ServerErrorException("您还不是创客无法发布商品");
            }
            if (model.id == 0) {
                var product = model.ToDtoObject<TokenBazaarProduct>();
                product.CreateTime = DateTime.Now.ToUnix();
                product.UpdateTime = DateTime.Now.ToUnix();
                product.MainImg = product.Imgs.ToObject<List<string>>().FirstOrDefault();
                product.Status = EBazaarProductStatus.Auditing;
                context.TokenBazaarProduct.Add(product);

                int r = _iUnitOfWork.Commit();
                return r > 0;

            } else {
                var product = context.TokenBazaarProduct.FindById(model.id);
                var oldimgs = product.Imgs.ToObject<List<string>>();
                model.ToDtoObject(product);
                product.Status = EBazaarProductStatus.Auditing;
                product.UpdateTime = DateTime.Now.ToUnix();
                product.MainImg = model.imgs.FirstOrDefault();

                int r = _iUnitOfWork.Commit("TokenBazaarProduct" + model.id);
                if (r > 0) {
                    if (model.imgs.Count > 0 && oldimgs.Count > 0) {
                        var oss = new AliyunOSS(DtoHelper._accessKeyId, DtoHelper._accessKeySecret, "");
                        //删除
                        oldimgs.Except(model.imgs).DataForEach(filter_id => {
                            oss.DeleteObject(DtoHelper.oss_bucketName, filter_id.Trim('/'));
                        });
                    }
                }
                return r > 0;
            }
        }
        /// <summary>
        ///获取商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public token_bazaar_product_dto GetProduct(long id) {
            var model = context.TokenBazaarProduct.Where(c => c.Id == id).FromCacheFirstOrDefault<TokenBazaarProduct, token_bazaar_product_dto>("TokenBazaarProduct" + id);
            return model;
        }
        /// <summary>
        /// 商品查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<token_bazaar_product_dto> Gets(BazaarProductQuery query) {
            var filter = PredicateBuilder.True<TokenBazaarProduct>();
            if (!query.is_all) {
                filter = filter.And(c => c.Num >= 1 && c.Status <= EBazaarProductStatus.Upper&&c.MarketPrice>0);
            }
            if (!string.IsNullOrEmpty(query.merchant_name)) {
                filter = filter.And(c => c.Merchant.Name.Contains(query.merchant_name) || c.Merchant.Mobile.Contains(query.merchant_name));
            }
            if (query.is_del.HasValue) {
                filter = filter.And(c => c.IsDel == query.is_del.Value);
            }
            if (query.merchant_id.HasValue) {
                filter = filter.And(c => c.MerchantId == query.merchant_id);
            }
            if (!string.IsNullOrEmpty(query.product_name))
                filter = filter.And(c => c.ProductName.Contains(query.product_name));
            if (query.start_time.HasValue) {
                long startTime = query.start_time.Value.ToUnix();
                filter = filter.And(c => c.UpdateTime >= startTime);
            }
            if (query.end_time.HasValue) {
                long endTime = query.end_time.Value.AddDays(1).ToUnix();
                filter = filter.And(c => c.UpdateTime <= endTime);
            }

            if (query.status.GetValueOrDefault(-1) > -1) {
                filter = filter.And(c => c.Status == (EBazaarProductStatus)query.status);
            }
            if (query.category_id.GetValueOrDefault(0) > 0) {
                filter = filter.And(c => c.CategoryId == query.category_id.Value);
            } else if (query.is_recommend.HasValue) {
                filter = filter.And(c => c.IsRecommend == query.is_recommend.Value);
            }
            return context.TokenBazaarProduct.FromCachePaged<TokenBazaarProduct, token_bazaar_product_dto>(query.page, query.size, filter, orderBy => orderBy.OrderBy(c => c.Status).ThenByDescending(c => c.UpdateTime));
        }
        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="id"></param>
        /// <param name="merchantId"></param>
        /// <returns></returns>
        public bool Delete(long id, long merchantId) {
            var model = context.TokenBazaarProduct.Where(s => s.Id == id && s.MerchantId == merchantId).FirstOrDefault();
            model.IsDel = true;
            var r = _iUnitOfWork.Commit("TokenBazaarProduct" + id);
            return r > 0;
        }
        /// <summary>
        /// 下架商品
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Down(long id) {
            var model = context.TokenBazaarProduct.FindById(id);
            if (model.Status != EBazaarProductStatus.Upper) {
                throw new ServerErrorException("只有上架的商品才能下架");
            }
            model.Status = EBazaarProductStatus.Down;
            var r = _iUnitOfWork.Commit("TokenBazaarProduct" + id);
            return r > 0;
        }
        /// <summary>
        /// 推荐/取消推荐
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isRecommend"></param>
        /// <returns></returns>
        public bool Recommend(long id, bool isRecommend) {
            var model = context.TokenBazaarProduct.FindById(id);
            model.IsRecommend = isRecommend;
            var r = _iUnitOfWork.Commit("TokenBazaarProduct" + id);
            return r > 0;
        }
        /// <summary>
        /// 审核商品
        /// </summary>
        /// <param name="id"></param>
        /// <param name="categoryId"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public bool Audit(long id, long categoryId, int status, decimal price, string remark) {
            var model = context.TokenBazaarProduct.FindById(id);
            if (model.Status != EBazaarProductStatus.Auditing) {
                throw new ServerErrorException("只有待审核的商品才能审核");
            }
            if (price == 0)
                throw new ServerErrorException("红钻价格不能为0");
            model.CategoryId = categoryId;
            model.Status = (EBazaarProductStatus)status;
            model.Price = price;
            if (!string.IsNullOrEmpty(remark)) {
                if (model.Status == EBazaarProductStatus.Down) {
                    //保存消息
                    var replyMessage = new MessagePush();
                    replyMessage.MerchantId = model.MerchantId;
                    replyMessage.Type = MsgType.BazaarPass;
                    replyMessage.Title = "集市商品审核未通过";
                    replyMessage.ShortContent = string.Format("您集市商品{0}审核未通过审核！", model.ProductName);
                    replyMessage.Content = remark;
                    replyMessage.Ext = "{}";
                    replyMessage.CreateTime = DateTime.Now.ToUnix();
                    replyMessage.ObjectId = model.Id;
                    replyMessage.Url = t_RequestMethod.token_url + "bazaarproduct/detail/" + model.Id;
                    context.MessagePushs.Add(replyMessage);

                    //发送消息
                    try {
                        JPushHelp jPushHelp = new JPushHelp(t_RequestMethod.push_app_key, t_RequestMethod.push_app_secret);
                        jPushHelp.Push(replyMessage.Title, replyMessage.Content, (int)replyMessage.Type, replyMessage.ObjectId.Value, new List<string> { model.Merchant.Mobile }, replyMessage.Url);
                    }
                    catch (Exception) { }
                } else if (model.Status == EBazaarProductStatus.Upper) {
                    //保存消息
                    var replyMessage = new MessagePush();
                    replyMessage.MerchantId = model.MerchantId;
                    replyMessage.Type = MsgType.BazaarPass;
                    replyMessage.Title = "集市商品审核通过";
                    replyMessage.ShortContent = string.Format("您集市商品{0}审核通过审核！", model.ProductName);
                    replyMessage.Content = remark;
                    replyMessage.Ext = "{}";
                    replyMessage.CreateTime = DateTime.Now.ToUnix();
                    replyMessage.ObjectId = model.Id;
                    replyMessage.Url = t_RequestMethod.token_url + "bazaarproduct/detail/" + model.Id;
                    context.MessagePushs.Add(replyMessage);

                    //发送消息
                    try {
                        JPushHelp jPushHelp = new JPushHelp(t_RequestMethod.push_app_key, t_RequestMethod.push_app_secret);
                        jPushHelp.Push(replyMessage.Title, replyMessage.Content, (int)replyMessage.Type, replyMessage.ObjectId.Value, new List<string> { model.Merchant.Mobile }, replyMessage.Url);
                    }
                    catch (Exception) { }
                }
            }
            var r = _iUnitOfWork.Commit("TokenBazaarProduct" + id, "MessagePush" + model.MerchantId);
            return r > 0;
        }
    }
}
